<template>
  <!-- 正常单据 -->
  <div>
    <el-table-form ref="form" :model="query">
      <el-form-item class="merge-item">
        <el-select ref="qtype" v-model="qtype" style="width: 170px; margin-right: 2px;">
          <el-option label="客户编号" value="csmCode" />
          <el-option label="客户电话" value="csmPhone" />
          <el-option label="客户名称" value="csmName" />
          <el-option label="押金单号" value="depositCode" />
          <el-option label="备注" value="remark" />
          <el-option label="经办人" value="transactor" />
          <el-option label="商品描述" value="goodsDesc" />
          <el-option label="收款人" value="depReceiver" />
          <el-option label="收据单号" value="billCode" />
          <el-option label="退款人" value="operator" />
          <el-option label="身份证号" value="csmCardNo" />
        </el-select>
        <el-input v-model="param1" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item :table-form-merge="2" class="merge-item">
        <el-select ref="timetype" v-model="timetype" style="width: 170px; margin-right: 2px;">
          <el-option label="押金登记时间" value="createTime" />
          <el-option label="开始时间" value="beginDt" />
          <el-option label="结束时间" value="endDt" />
          <el-option label="经办时间" value="transactDt" />
          <el-option label="审核时间" value="auditDt" />
          <el-option label="消单时间" value="operateDt" />
        </el-select>
        <el-date-picker
          v-model="date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item label="押瓶机构" prop="orgSNNo">
        <el-tree-select
          v-model="query.ckOrgSNNo"
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择组织机构',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'default-expand-all': true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item label="客户类型" class="merge-item">
        <el-select ref="csmType" v-model="query.csmType" clearable placeholder="请选择">
          <el-option v-for="(v,i) in entTypeList" :key="i" :label="v.desc" :value="v.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="单据状态" class="merge-item">
        <el-select ref="depStatus" v-model="query.depStatus" placeholder="请选择">
          <el-option v-for="(v,i) in depositStatusMap" :key="i" :label="v.desc" :value="v.value" />
          <!-- <el-option label="未审核" :value="1" />
          <el-option label="已审核" :value="2" />
          <el-option label="已消单" :value="3" />
          <el-option label="已作废" :value="4" />
          <el-option label="审核不通过" :value="5" />
          <el-option label="消单待确认" :value="6" /> -->
        </el-select>
      </el-form-item>
      <el-form-item label="排序" class="merge-item" placeholder="请选择">
        <el-select ref="orderby" v-model="query.orderby">
          <el-option label="押金登记时间" :value="2" />
          <el-option label="开始时间" :value="3" />
          <el-option label="结束时间" :value="4" />
          <el-option label="经办时间" :value="5" />
          <el-option label="审核时间" :value="6" />
          <el-option label="消单时间" :value="7" />
        </el-select>
      </el-form-item>
      <el-form-item label="支付方式" class="merge-item">
        <el-select ref="paymentMethod" v-model="query.paymentMethod" placeholder="请选择">
          <el-option label="现金" :value="1" />
          <el-option label="微信支付" :value="2" />
          <el-option label="支付宝" :value="128" />
          <el-option label="工行支付" :value="1024" />
        </el-select>
      </el-form-item>
      <el-form-item label="支付状态" class="merge-item">
        <el-select ref="payStatus" v-model="query.payStatus" placeholder="请选择">
          <el-option label="已支付" :value="3" />
          <el-option label="未支付" :value="1" />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>

    <div style="margin-bottom: 10px;">
      <el-button type="primary" icon="el-icon-circle-plus-outline" @click="openNormalReceiptsAdd">新增</el-button>
      <!-- <el-button type="primary" icon="el-icon-s-check">批量审核</el-button> -->
      <el-button type="primary" icon="el-icon-download" @click="exportFile">导出</el-button>
    </div>

    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data.rows"
      highlight-current-row
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />

    <normal-receipts-add ref="normalReceiptsAdd" />
    <popups ref="popups" />
    <receipt ref="receipt" @upDataReceipt="upDataTable" />
    <depositAudit ref="depositAudit" @depUpDataTable="upDataTable" />
    <orderConfirmation ref="orderConfirmation" @upDataTable="upDataTable" />
    <transferInformation ref="transferInformation" />
    <turnOrder ref="turnOrder" @turnUpDataTable="upDataTable" />
    <depositEdit ref="depositEdit" />
  </div>
</template>

<script>
  import NormalReceiptsAdd from './NormalReceiptsAdd'
  import DepositEdit from './DepositEdit'
  import { formatColumnMap, parseTime } from '@/utils'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import Popups from './Popups'
  import Receipt from './Receipt'
  import DepositAudit from './DepositAudit'
  import OrderConfirmation from './OrderConfirmation'
  import TransferInformation from './TransferInformation'
  import TurnOrder from './TurnOrder'
  import { queryTheDepositList, queryCsmTypeMap, gasCheckTodoExport, queryExportDomain, queryRevertReturn, queryRevertAudit, queryCashPledgeInvalid, customerInfo, queryCashPledgeDetail } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import moment from 'dayjs'

  export default {
    name: 'normal-receipts-tab',
    components: {
      Popups, NormalReceiptsAdd, Receipt, DepositAudit, OrderConfirmation, TransferInformation, TurnOrder, DepositEdit
    },
    data() {
      return {
        qtype: 'depositCode',
        param1: '',
        timetype: 'createTime',
        exportDomain: {},
        entTypeList: [], // 客户类型
        date: [],
        treeData: [],
        query: {
          csmType: '', // 客户类型
          ckOrgSNNo: '',
          depositCode: '',
          depStatus: '',
          payStatus: '',
          paymentMethod: '',
          orderby: 2,
          createTime: '',
          createTimeEnd: ''
        },
        depositStatusMap: [
          { 'value': 1, 'desc': '未审核', 'key': 'NOT_AUDIT' },
          { 'value': 2, 'desc': '已审核', 'key': 'AUDITED' },
          { 'value': 3, 'desc': '已消单', 'key': 'RETURNED' },
          { 'value': 4, 'desc': '已作废', 'key': 'VOIDED' },
          { 'value': 5, 'desc': '审核不通过', 'key': 'NOT_PASS' },
          { 'value': 6, 'desc': '消单待确认', 'key': 'RETURN_APPLY' }
        ],
        tableData: {
          total: 0,
          column: [
            // {
            //   type: 'selection'
            // },
            {
              prop: 'depositUrl',
              label: '图片',
              width: 50,
              render: (h, { row }) => <span>{row.depositUrl && <i class='el-icon-picture'></i>}</span>
            },
            {
              prop: 'depositCode',
              label: '押金单号',
              width: 130
            },
            {
              prop: 'csmCode',
              label: '客户编号',
              width: 110
            },
            {
              prop: 'csmName',
              label: '客户名称',
              width: 160
            },
            {
              prop: 'csmCardNo',
              label: '身份证号',
              width: 180
            },
            {
              prop: 'csmType',
              label: '客户类型',
              width: 100,
              render: (h, { row }) => <span>{ row.csmType && formatColumnMap(this.entTypeList, 'value', row.csmType, 'desc') }</span>
            },
            {
              prop: 'csmPhone',
              label: '联系电话',
              width: 130
            },
            {
              prop: 'totalCount',
              label: '总数量',
              width: 80
            },
            {
              prop: 'goodsDesc',
              label: '商品描述',
              width: 200
            },
            {
              prop: 'totalDeposit',
              label: '总押金',
              width: 120
            },
            {
              prop: 'fee1',
              label: '手续费',
              width: 120,
              render: (h, { row }) => <span>{ row.fee1 || <span>0.00</span> }</span>
            },
            {
              prop: 'ckOrgName',
              label: '押瓶机构',
              width: 180
            },
            {
              prop: 'returnOrgName',
              label: '退瓶机构',
              width: 180
            },
            {
              prop: 'createTime',
              label: '押金登记时间',
              width: 200,
              render: (h, { row }) => <span>{ row.createTime && parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'depStatus',
              label: '单据状态',
              width: 110,
              render: (h, { row }) => <span style={this.statusFormat(row.depStatus)}>{this.depositStatusMap.find(v => row.depStatus === v.value).desc}</span>
            },
            {
              prop: 'auditDt',
              label: '审核时间',
              width: 200,
              render: (h, { row }) => <span>{ (row.depStatus === 2 || row.depStatus === 3) && parseTime(row.auditDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'remark',
              label: '备注',
              width: 110
            },
            {
              prop: 'beginDt',
              label: '开始时间',
              width: 200,
              render: (h, { row }) => <span>{ row.beginDt && parseTime(row.beginDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'endDt',
              label: '结束时间',
              width: 200,
              render: (h, { row }) => <span>{ row.endDt && parseTime(row.endDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'transactor',
              label: '经办人',
              width: 110
            },
            {
              prop: 'depReceiver',
              label: '收款人',
              width: 110
            },
            {
              prop: 'operator',
              label: '退款人',
              width: 110
            },
            {
              prop: 'transactDt',
              label: '经办时间',
              width: 200,
              render: (h, { row }) => <span>{ row.transactDt && parseTime(row.transactDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'operateDt',
              label: '消单时间',
              width: 200,
              render: (h, { row }) => <span>{ (row.depStatus === 3 || row.depStatus === 6) && parseTime(row.operateDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'billCode',
              label: '收据单号',
              width: 110
            },
            {
              prop: 'paymentMethod',
              label: '支付方式',
              width: 110,
              render: (h, { row }) => <span>{this.paymentMethodFormat(row)}</span>
            },
            {
              prop: 'payStatus',
              label: '支付状态',
              width: 110,
              render: (h, { row }) => <span>{this.payStatusFormat(row)}</span>
            },
            {
              label: '操作',
              align: 'center',
              fixed: 'right',
              width: 300,
              render: (h, { row, $index }) => {
                return (
                  <div>
                    {(row.depStatus === 1 && row.payStatus === 1 || row.depStatus === 1 && row.payStatus === 3 || row.depStatus === 5) && <el-link size='mini' onClick={() => this.openNormalReceipts(row)}> 编辑 </el-link>}
                    {(row.payStatus === 1) && <el-link size='mini' onClick={() => this.openReceipt(row)}> 收款 </el-link>}
                    {(row.depStatus === 1 && row.payStatus === 1 || row.depStatus === 1 && row.payStatus === 3) && <el-link size='mini' onClick={() => this.openDepositAudit(row)}> 审核 </el-link>}
                    {row.depStatus === 2 && <el-link size='mini' onClick={() => this.openTurnOrder(row)}>退瓶消单</el-link>}
                    {(row.depStatus === 6) && <el-link size='mini' onClick={() => this.openOrderConfirmation(row)}> 消单确认 </el-link>}
                    {(row.depStatus === 1 && row.payStatus === 1 || row.depStatus === 1 && row.payStatus === 3 && row.paymentMethod === 1) && <el-link size='mini' type='danger' onClick={() => this.onCancellation(row)}> 作废 </el-link>}
                    <el-link size='mini' onClick={() => this.showDeposit(row)}> 押金明细 </el-link>
                    {row.depStatus === 2 && <el-link size='mini' onClick={() => this.revertAudit(row)}> 租瓶反审核 </el-link>}
                    {(row.depStatus === 3) && <el-link size='mini' onClick={() => this.revertReturn(row)}> 退瓶反消单 </el-link>}
                    {(row.payStatus !== 1) || (row.depStatus === 2) && <el-link size='mini' onClick={() => this.printDep(row)}> 打印 </el-link>}
                    <el-link size='mini' onClick={() => this.showTraceWin(row)}> 流转信息 </el-link>
                  </div>
                )
              }
            }
          ],
          data: {
            rows: []
          }
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList'
      ])
    },
    async created() {
      await this.getTreeData()
      await this.getEntType()
      await this.getExportDomain()
    },
    methods: {
      // 查询
      async search() {
        this.$refs.lbTable.fetch()
      },
      // 新增
      async openNormalReceiptsAdd() {
        this.$refs.normalReceiptsAdd.open()
      },
      // 编辑
      async openNormalReceipts(row) {
        console.log('......', row)
        const res = await customerInfo({ csmCode: row.csmCode })
        const res1 = await queryCashPledgeDetail({
          depCode: row.depositCode,
          depositId: row.depositId,
          depStatus: row.depStatus
        })
        console.log('res1钢瓶记录列表', res1)
        console.log(res, 'res')
        const obj = {
          ...res.data,
          depositCode: row.depositCode,
          depReceiver: row.depReceiver,
          calcType: row.calcType,
          fee1: row.fee1,
          billCode: row.billCode,
          paymentMethod: row.paymentMethod,
          remark: row.remark,
          depositDetails: res1.data.depositDetails
        }
        this.$refs.depositEdit.open(obj, 'edit')
      },
      // 收款支付
      openReceipt(row) {
        this.$refs.receipt.open(row)
      },
      // 审核
      openDepositAudit(row) {
        // if (row.depStatus !== 1) {
        //   this.$message({ message: '操作失败，请核实押金单状态', type: 'warning' })
        // } else if (row.depStatus === 1 && row.payStatus === 1) {
        //   this.$message({ message: '请先收取钢瓶押金', type: 'warning' })
        // } else {
        //   }
        this.$refs.depositAudit.open(row)
      },
      // 消单确认
      openOrderConfirmation(row) {
        this.$refs.orderConfirmation.open(row)
      },
      // 更新表格
      upDataTable() {
        console.log('gengxinl ')
        this.$refs.lbTable.fetch()
      },
      // 退瓶消单
      openTurnOrder(row) {
        this.$refs.turnOrder.open(row)
      },
      // 作废
      onCancellation(row) {
        this.$confirm('确认要执行操作吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          const { status } = await queryCashPledgeInvalid({
            depCode: row.depositCode
          })
          if (status === 200) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.$refs.lbTable.fetch()
          }
        })
      },
      // 押金明细
      showDeposit(row) {
        console.log('押金明细', row)
        this.$refs.popups.open(row)
      },
      // 租瓶反审核
      revertAudit(row) {
        this.$confirm('是否确定执行租瓶反审核操作？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          const { status } = await queryRevertAudit({
            depositCode: row.depositCode
          })
          if (status === 200) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.$refs.lbTable.fetch()
          }
        })
      },
      // 退瓶反消单
      revertReturn(row) {
        this.$confirm('是否确定执行退瓶反消单操作？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          const { status } = await queryRevertReturn({
            depositCode: row.depositCode
          })
          if (status === 200) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.$refs.lbTable.fetch()
          }
        })
      },
      // 打印
      printDep(row) {
        console.log('打印', row)
      },
      // 流转信息
      showTraceWin(row) {
        this.$refs.transferInformation.open(row)
      },
      // 客户类型
      async getEntType() {
        const res = await queryCsmTypeMap()
        this.entTypeList = res.data
      },
      // 列表
      async fetchData({ currentPage, pageSize }) {
        const params = { ...this.query }
        params[this.qtype] = this.param1
        if (this.date.length === 2) {
          params[this.timetype] = moment(this.date[0]).format()
          params[`${this.timetype}End`] = moment(this.date[1]).format()
        }
        const query = {
          ...this._getQuery(params),
          currentPage,
          pageSize
        }
        const result = await queryTheDepositList(query)
        this.tableData.data.rows = result.data.rows
        if (currentPage === 1) {
          this.tableData.total = result.data.total
        }
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.orgName,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.orgSNNo = value.orgSNNo
      },
      // 导出
      async exportFile() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'info'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.tableData.column))
          copyColumn.pop()
          const str = {}
          copyColumn.forEach(item => {
            str[item.prop] = item.label
          })
          gasCheckTodoExport({
            paramInfo: _this._getQuery(_this.query),
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      // 获取导出域名
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain)
          .then((res) => {
            this.exportDomain = res.data
          })
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      // 颜色
      statusFormat(val) {
        var colorObj = {
          '1': 'color:#0033ff;', // 待审核
          '2': 'color:#333333;', // 已审核
          '3': 'color:#666666;', // 已消单
          '4': 'color:#666666;', // 已作废
          '5': 'color:#ff0000;', // 审核不通过
          '6': 'color:#0033ff;' // 消单待确认
        }
        return colorObj[val]
      },
      // 支付状态
      payStatusFormat(r) {
        if (r.payStatus === 1) {
          return '未支付'
        } else if (r.payStatus === 3) {
          return '已支付'
        } else {
          return ''
        }
      },
      // 支付方式
      paymentMethodFormat(r) {
        if (r.paymentMethod === 1) {
          return '现金'
        } else if (r.paymentMethod === 2) {
          return '微信支付'
        } else if (r.paymentMethod === 128) {
          return '支付宝'
        } else if (r.paymentMethod === 1024) {
          return '工行支付'
        } else {
          return ''
        }
      }
    }
  }
</script>

<style lang="scss" scoped>

</style>
